
/**
  ******************************************************************************
  * Copyright 2021 The grapilot Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       console.c
  * @author     baiyang
  * @date       2021-7-12
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include <finsh.h>
#include <string.h>
/*-----------------------------------macro------------------------------------*/
#define CONSOLE_BUFF_SIZE      1024
/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/

/*----------------------------------variable----------------------------------*/
static rt_device_t _console_dev = NULL;
static char _buffer[CONSOLE_BUFF_SIZE];
/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
uint32_t console_write(const char* content, uint32_t len)
{
    return rt_device_write(_console_dev, 0, (void*)content, len);
}

uint32_t console_printf(const char* fmt, ...)
{
    if (_console_dev == NULL) {
        return 0;
    }

    va_list args;
    int length;

    va_start(args, fmt);
    length = vsnprintf(_buffer, CONSOLE_BUFF_SIZE, fmt, args);
    va_end(args);

    return console_write(_buffer, length);
}

uint32_t console_printf_textv(const char *fmt, va_list arg_list)
{
    if (_console_dev == NULL) {
        return 0;
    }

    uint32_t length;
    char buffer[128];

    length = vsnprintf(buffer, sizeof(buffer), fmt, arg_list);

    return console_write(_buffer, length);
}

void console_panic(const char* fmt, ...)
{
    uint32_t len;

    if (_console_dev == NULL) {
        return;
    }

    va_list args;
    int length;

    va_start(args, fmt);
    length = vsnprintf(_buffer, CONSOLE_BUFF_SIZE, fmt, args);
    va_end(args);

    len = console_write(_buffer, length);

    // we will never get here, this just to silence a warning
    while (1) {}
}

int8_t console_init(void)
{
    int8_t res = 0;

    _console_dev = rt_device_find(RT_CONSOLE_DEVICE_NAME);

    if (_console_dev != NULL) {
        res = 1;
    }

    return res;
}
/*------------------------------------test------------------------------------*/


